import { reactive, inject, provide, toRaw } from 'vue';
import { ConsoleLogger } from '@/utils/debug-log';
import { ESubmitType, CurrentSubject, EMarkType } from '../types/jobs/homeWork';
import { ECommitStatus, ERejected, PlantHomeWork, StdHomeWork, SubjectInfo } from '../types/jobs';
import { AnswersID, AnswersTestID, StuID } from '../types';
import { getCHNumber } from '@/utils/chString';
import { ReqJobCorrectParam, ReqRevisalParam } from '../types/jobs/jobCorrect';

const console = new ConsoleLogger('学生作业');
const useCurrectStdSymbol = Symbol('useCurrectStd store');

export interface ICurrectStdState {
  /**是否点评页面 */
  remarkStatus: boolean;
  homework: PlantHomeWork;
  /**当前子题和小题 */
  currentSubjectList: Array<CurrentSubject>;
  /**当前子题和小题 */
  currentSubject?: CurrentSubject;
  /**题目列表 */
  subjectList?: Array<SubjectInfo>; //
  /**订正列表。 与题目列表互斥 */
  wrong_test_ids?: Array<{ id: AnswersID; test_id: AnswersTestID }>; //
  /**当前选择学生列表 */
  currentStdHomeWork?: StdHomeWork;
  /**提交状态 */
  submitType: ESubmitType;
  /**作业提交参数 ReqJobCorrectParam*/
  reqJobCorrectParam?: Partial<ReqJobCorrectParam>;
  /**作业订正参数 ReqRevisalParam*/
  reqRevisalParam?: Partial<ReqRevisalParam>;
  /**打分 状态 */
  markStatusInfo: { [test_id: AnswersTestID]: { markType: EMarkType; markNum: number } };
}

export interface IUseCurrectStdStoreFn {
  (): IUseCurrectStdStore;
  __CurrentStore?: IUseCurrectStdStore;
}

export interface IUseCurrectStdStore {
  state: ICurrectStdState;
  /**初始化作业展示，提交参数业务 */
  initSubject: () => Promise<void>;
  /**参数获取 */
  getReqParam: () => Partial<ReqJobCorrectParam> | Partial<ReqRevisalParam> | undefined;
  /**获取小问批改业务状态 */
  getCorrectStatus: () => { text: string; status: boolean };
  /**选择学生进入批改状态 */
  selectStudent: (stdinfo: StdHomeWork, homework: PlantHomeWork) => Promise<void>;
  /**获取mark状态 */
  getMarkStatus: () => { markType: EMarkType; markNum: number };
}
export const loginStatus = { CurrectStd: {}, isLoginStatus: false };
/**
 *  * useCurrectStdStore 用户hooks.
 * @function
 * @params {ICurrectStdState} userState - 用户信息.
 * @returns store extend IUseCurrectStdStore
 */
export const useCurrectStdProvide: () => IUseCurrectStdStore = () => {
  const rs = window.localStorage.getItem('CurrectStdtate');
  const stateHistory: any = JSON.parse(rs ? rs : '{}');

  const state = reactive<ICurrectStdState>({
    currentSubjectList: [],
    currentSubject: {},
    subjectList: [],
    wrong_test_ids: [],
    currentStdHomeWork: {},
    reqJobCorrectParam: {},
    submitType: ESubmitType.frist,
    reqRevisalParam: {},
    ...stateHistory,
    markStatusInfo: {},
    remarkStatus: false
  });
  const selectStudent = async (stdinfo: StdHomeWork, homework: PlantHomeWork) => {
    state.currentStdHomeWork = stdinfo;
    state.homework = homework;
    await initSubject();
    state.currentSubject = state.currentSubjectList.length > 0 ? state.currentSubjectList[0] : undefined;
    state.markStatusInfo = {};
    window.localStorage.setItem('CurrectStdtate', JSON.stringify(toRaw(state)));
    //初始化提交参数
  };

  const getReqParam = () => {
    return state.submitType === ESubmitType.frist ? state.reqJobCorrectParam : state.reqRevisalParam;
  };

  /**批改状态获取 */
  const getCorrectStatus: () => { text: string; status: boolean } = () => {
    let currectText = '';
    let status = true;
    let idxStr = '';
    (state.submitType === ESubmitType.frist ? state.reqJobCorrectParam : state.reqRevisalParam)?.correct_infos?.forEach((node) => {
      const scores = node.test_infos?.filter((v) => v.stu_score === undefined || v.audio_url === '');
      //获取题序号
      scores?.forEach((score) => {
        state.currentSubjectList?.forEach((node) => {
          if (node.test_id == score.test_id) {
            idxStr += node.name + ',\n';
            status = false;
          }
        });
      });
    });
    currectText = '无法保存，小问:\n' + idxStr + '无批改记录';

    return { text: currectText, status: status };
  };

  /**初始化作业展示，提交参数业务 */
  const initSubject = async () => {
    state.currentSubjectList = [];
    const subjectList = state.homework.details;
    if (state.currentStdHomeWork && state.currentStdHomeWork.correct?.audio_url === '') {
      if (subjectList && subjectList.length > 0) {
        state.subjectList = subjectList;
        subjectList.forEach((node, idx) => {
          node.tests?.forEach((val, i) => {
            state.currentSubjectList.push({
              name: '第' + getCHNumber(node.id) + '题' + '第' + getCHNumber(i + 1) + '问',
              idx: idx + 1,
              id: node.id,
              ...val
            });
          });
        });
        state.submitType = ESubmitType.frist;
        //互斥参数致空
        state.reqRevisalParam = {};
        //初始化提交参数
        state.reqJobCorrectParam = {
          commit_id: state.currentStdHomeWork.commit.commit_id,
          work_id: state.homework.id!,
          work_type: state.homework.type!,
          stu_name: state.currentStdHomeWork.stu_name,
          correct_infos: subjectList.map((node) => ({
            id: node.id,
            test_infos: node.tests.map((v) => ({
              test_id: v.test_id,
              test_score: v.test_score,
              stu_score: v.test_score,
              audio_url: '',
              test_type: v.test_type
            }))
          }))
        };
      }
    }
    if (state.currentStdHomeWork && state.currentStdHomeWork.correct?.audio_url != '') {
      // debugger;
      if (subjectList && subjectList.length > 0) {
        state.wrong_test_ids = state.currentStdHomeWork.wrong_test_ids;
        const correct_infos_param: any = [];
        subjectList.forEach((node, idx) => {
          node.tests?.forEach((val, i) => {
            if (state.wrong_test_ids && state.wrong_test_ids?.filter((v) => v.id === node.id).length > 0) {
              correct_infos_param.push({
                test_id: val.test_id,
                test_score: val.test_score,
                stu_score: val.test_score,
                audio_url: '',
                test_type: val.test_type
              });
              state.currentSubjectList.push({
                name: '第' + getCHNumber(node.id) + '题' + '第' + getCHNumber(i + 1) + '问',
                idx: idx + 1,
                id: node.id,
                ...val
              });
            }
          });
        });
        state.submitType = ESubmitType.wrong;
        //互斥参数致空
        state.reqJobCorrectParam = {};
        //初始化提交参数
        state.reqRevisalParam = {
          commit_id: state.currentStdHomeWork.commit.commit_id,
          work_id: state.homework.id!,
          work_type: state.homework.type!,
          stu_name: state.currentStdHomeWork.stu_name,
          correct_infos: subjectList
            .filter((v) => {
              if (state.wrong_test_ids && state.wrong_test_ids.filter((w) => w.id === v.id).length > 0) {
                return true;
              } else {
                return false;
              }
            })
            .map((node) => ({
              id: node.id,
              test_infos: correct_infos_param
            }))
        };
      }
    }
  };

  const getMarkStatus = () => {
    if (state.currentSubject && state.currentSubject.test_id && typeof state.markStatusInfo[state.currentSubject.test_id] === 'undefined') {
      store.state.markStatusInfo[state.currentSubject.test_id] = { markType: EMarkType.none, markNum: 0 };
    }
    return state.markStatusInfo[store.state.currentSubject?.test_id!];
  };
  const store: IUseCurrectStdStore = {
    state,
    getReqParam,
    initSubject,
    getCorrectStatus,
    selectStudent,
    getMarkStatus
  };

  provide(useCurrectStdSymbol, { ...store });

  return store;
};

/**
 *  * useCurrectStdStore 用户hooks.
 * @function
 * @returns store extend IUseCurrectStdStore
 */
export const useCurrectStdStore: IUseCurrectStdStoreFn = () => {
  const store: IUseCurrectStdStore = inject(useCurrectStdSymbol) as IUseCurrectStdStore;
  return store;
};
